package com.hliushi.learn.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;

/**
 * @ClassName JacksonConfig
 * @Description jackson中对null的处理, Springboot汇总默认使用的JSON解析框架是Jackson
 * @Author hliushi
 * @Date 2021/7/5 20:39
 * @Version V1.0
 **/
@Configuration
public class JacksonConfig {


    /**
     * jackson中对null的处理, 所有的null在转为JSON都会变成 "" 这种空字符串
     *
     * @param builder
     * @return objectMapper
     */
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jackObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();

        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });

        // objectMapper.getSerializerProvider().setNullKeySerializer(new JsonSerializer<Object>() {
        //     @Override
        //     public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        //         gen.writeString("");
        //     }
        // });

        return objectMapper;
    }
}
